package chenshuaiwen.util;

import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 工具类-单例工厂
 *
 * @author 陈帅闻
 * @since 2025/6/16 13:49
 */
public class SingletonFactory {

    private  static final Map< Class<?>, Object> instanceMap = new ConcurrentHashMap<>();
    public static <T> T getInstance(Class<T> clazz) {
        if(clazz == null){
            throw new RuntimeException("未知的类型");
        }
        if(!instanceMap.containsKey(clazz)){
            try{
                Constructor<T> constructor = clazz.getDeclaredConstructor();
                constructor.setAccessible(true);
                T instance = constructor.newInstance();
                instanceMap.put(clazz, instance);
            }catch (Exception e){
                throw new IllegalArgumentException("创建单例模式失败" + clazz.getSimpleName(), e);
            }
        }
        @SuppressWarnings("unchecked")
        T instance = (T) instanceMap.get(clazz);
        return instance;


    }
}
